from django.db.models.signals import post_delete
from django.contrib.contenttypes.models import ContentType

from slots.models import Slot, GenericIntermediary, Transition


def delete_slots(sender, instance, **kwargs):
    # find the intermediaries which have the sender
    ct = ContentType.objects.get_for_model(sender)
    # left: the intermediaries which have things scheduled against them
    left_gi_set = GenericIntermediary.objects.filter(left=ct)
    # right: the things which are scheduled
    right_gi_set = GenericIntermediary.objects.filter(right=ct)
    # now find the slots containing this instance and delete them
    # we can't catenate the query sets because the left/rightness is
    # important
    for gi in left_gi_set:
        Slot.objects.filter(relationship=gi,
                            against_object_id=instance.id).delete()
    for gi in right_gi_set:
        Slot.objects.filter(relationship=gi,
                            slotted_object_id=instance.id).delete()

def delete_transitions(sender, instance, **kwargs):
    # find the transitions which have the sender
    ct = ContentType.objects.get_for_model(sender)
    # now find the transitions which have this instance on either side of the
    # relationship, and delete them
    if hasattr(instance,'id'):
        Transition.objects.filter(referenced_model=ct,
                                referenced_id=instance.id).delete()
        Transition.objects.filter(referring_model=ct,
                                referring_id=instance.id).delete()

post_delete.connect(delete_slots)
post_delete.connect(delete_transitions)
